package jrmob.yonyou.com.commonlib.app_config_tool.tool.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.location.LocationManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import jrmob.yonyou.com.commonlib.R;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.MobileDevice_lib;

/**
 * 描述: 移动工具类
 *
 * @author zhangg
 * @上午10:00:07
 */
public class MobUtils {

    public static String getDeviceId(Context context) {
        boolean isflag = false;
        String temp = "";
        try {
            temp = MobileDevice_lib.getDeviceInfo(context).optString("deviceid", "");
            return temp;
        } catch (JSONException e) {
            LogUtils.e(e);
            isflag = true;
            e.printStackTrace();
        } finally {
            if (isflag) {
                temp = "";
            }
        }
        return temp;
    }

    /**
     * 根据包名判断应用是否存在
     * @param context
     * @param packageName
     * @return
     */
    public static boolean checkApplication(Context context,String packageName) {
        if (packageName == null || "".equals(packageName)){
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 判断是否存在 activity
     * @param context
     * @param packageName
     * @param activityName
     * @return
     */
    public static boolean isExistActivity(Context context,String packageName ,String activityName) {

        Intent intent = new Intent();
        intent.setClassName(packageName, activityName);
        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent, 0);
        if (list != null && list.size() > 0) {
            // 说明系统中存在这个activity
            return true;
        }
        return false;


    }


    /**
     * 得到自定义的progressDialog
     *
     * @param context
     * @param msg
     * @return
     * @author zhangg
     */
    public static Dialog createLoadingDialog(Context context, String msg) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View v = inflater.inflate(R.layout.loading_dialog_lib, null);// 得到加载view
        LinearLayout layout = (LinearLayout) v.findViewById(R.id.dialog_view);// 加载布局
        // main.xml中的ImageView
        // ImageView spaceshipImage = (ImageView) v.findViewById(R.id.img);
        TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context,
                R.anim.loading_animation_lib);
        // 使用ImageView显示动画
        // spaceshipImage.startAnimation(hyperspaceJumpAnimation);
        tipTextView.setText(msg);// 设置加载信息
        Dialog loadingDialog = new Dialog(context, R.style.loading_dialog);// 创建自定义样式dialog
        loadingDialog.setCancelable(false);// 不可以用“返回键”取消
        loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
        return loadingDialog;

    }

    /**
     * 判断界面是否被劫持
     * @param context
     * @return
     */
    public boolean isRealSelfEnvirment(Context context) {
        boolean isReal = AntiHijackingUtil.checkActivity(context);
        if (isReal) {
            return true;
        } else {
            Toast.makeText(context, "不安全", Toast.LENGTH_SHORT).show();
        }
        return false;
    }

    /**
     * 将10进制颜色值转换成16进制。
     */
    private String getHexString(int value) {
        String hexString = Integer.toHexString(value);
        if (hexString.length() == 1) {
            hexString = "0" + hexString;
        }
        return hexString;
    }

    /**
     * SD卡是否存在
     *
     * @return
     */
    public static boolean isExistSDCard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }


    /**
     * SDcard 剩余容量
     *
     * @return
     */
    public static long getSDFreeSize() {
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
    }


    /**
     * SDCard 总容量
     *
     * @return
     */
    public static long getSDCardAllSize() {
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //获取所有数据块数
        long allBlocks = sf.getBlockCount();
        //返回SD卡大小
        //return allBlocks * blockSize; //单位Byte
        //return (allBlocks * blockSize)/1024; //单位KB
        return (allBlocks * blockSize) / 1024 / 1024; //单位MB
    }


    private void openGPSSettings(Context context) {
        LocationManager alm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (alm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(context, "GPS模块正常", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(context, "请开启GPS", Toast.LENGTH_SHORT).show();
        //Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
        //startActivityForResult(intent, 0); //此为设置完成后返回到获取界面
    }


    //sim卡是否可读
    public static boolean isCanUseSim(Context context) {
        try {
            TelephonyManager mgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

            return TelephonyManager.SIM_STATE_READY == mgr
                    .getSimState();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 功能: 获取系统内存(这个只是java 的方法,不是Android特有的)
     * <p>
     * 日 期: 2016/8/6
     *
     * @author zhangg
     */
    public static double getPercentRAM() {
        double total = Runtime.getRuntime().totalMemory();
        double free = Runtime.getRuntime().freeMemory();
        return (1 - (free / total)) * 100;
    }

    /**
     * 功能:获取android当前可用内存大小
     * <p/>
     * 日 期: 2016/8/5
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        //boolean islowmemory = mi.lowMemory; // 是否是低内存
        //mi.availMem; 当前系统的可用内存
        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }


    public static String getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;

        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小

            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }

            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();

        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }


    /**
     * 功能:  获取当前手机内存利用率
     * <p>
     * 日 期: 2016/8/5
     */
    public static String getMemoryUseRate(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        double initial_memory = 0;
        String returnValue = "";
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(
                    localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            initial_memory = Integer.valueOf(arrayOfString[1]).intValue() * 1024;// 获得系统总内存，单位是KB，乘以1024转换为Byte
            localBufferedReader.close();
            double result = (mi.availMem / initial_memory) * 100;

            DecimalFormat df = new DecimalFormat("0.00");//格式化小数，不足的补0
            returnValue = df.format(result);//返回的是String类型的


        } catch (Exception e) {
            ((BaseActivityMob_lib) context).showMessage(e + "");
            returnValue = "";
        } finally {
            return returnValue;
        }
    }


    /**
     * 功能:判断当前设备是否是模拟器。如果返回TRUE，则当前是模拟器，不是返回FALSE
     * <p/>
     * 日 期: 2016/7/31
     */
    public static boolean isEmulator(Context context) {
        TelephonyManager tm = null;
        boolean isEmulator = true;
        try {
            tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
        } catch (Exception ioe) {
        } finally {
            isEmulator = false;
        }
        if (null != tm) {
            String imei = tm.getDeviceId();
            if (imei != null && imei.equals("000000000000000")) {
                isEmulator = true;
            } else {
                isEmulator = (Build.MODEL.equals("sdk"))
                        || (Build.MODEL.equals("google_sdk"));
            }
        }
        return isEmulator;

    }

    /**
     * 功能: 判断app是否在前台还是在后台运行
     * author :  zhangg
     * 日 期: 2016/7/27
     */
    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                    /*
                    BACKGROUND=400 EMPTY=500 FOREGROUND=100
                    GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                     */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 约束精度
     *
     * @param f   要约束的数值
     * @param num 要约束的位数
     * @return
     */
    public static String calculateDegree(double f, int num) {
        NumberFormat nFormat = NumberFormat.getNumberInstance();
        nFormat.setMinimumFractionDigits(num);
        return nFormat.format(f);
    }

    /**
     * 获取位置信息: locationManager
     */
    public LocationManager getLocationManager() {
        String serviceString = Context.LOCATION_SERVICE;
        LocationManager LocationManager = (LocationManager) UiUtils.getContext().getSystemService(
                serviceString);
        return LocationManager;
    }


    /**
     * 获取设备屏幕分辨率(得到手机屏幕高度： dm.heightPixels; 得到手机屏幕宽度dm.widthPixels; )
     *
     * @param context
     * @author zhangg
     */
    @SuppressWarnings("unused")
    private DisplayMetrics getMetrics(BaseActivityMob_lib context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    /**
     * Android判断应用是否存在 (通过包名判断)
     *
     * @param packageName
     * @return
     */
    public boolean checkBrowser(String packageName) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ApplicationInfo info = UiUtils.getContext().getPackageManager()
                    .getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return null != info;
        } catch (NameNotFoundException e) {
            return false;
        }
    }


    /**
     * 获取当前app版本 eg: 1 等
     *
     * @return
     */
    public int getVersionCode() {
        try {
            return UiUtils.getContext().getPackageManager().getPackageInfo("", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取当前app版本名称
     *
     * @return
     */
    public String getVersionName() {
        try {
            return UiUtils.getContext().getPackageManager().getPackageInfo("", 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "未知";
    }


    /**
     * 设置屏幕透明度
     *
     * @param context
     * @param bgAlpha
     */
    public static void setBackgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().setAttributes(lp);
    }

    /***
     * 写对象
     *
     * @param sp
     * @param key
     * @param object
     * @author zhangg
     */
    public static void writeObject(SharedPreferences sp, String key, Object object) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        try {
            out = new ObjectOutputStream(baos);
            out.writeObject(object);
            String objectVal = new String(Base64.encode(baos.toByteArray(), Base64.DEFAULT));
            Editor editor = sp.edit();
            editor.putString(key, objectVal);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * 读对象
     *
     * @param sp
     * @param key
     * @param clazz
     * @return
     * @author zhangg
     */
    @SuppressWarnings("unchecked")
    public static <T> T readObject(SharedPreferences sp, String key, Class<T> clazz) {
        if (sp.contains(key)) {
            String objectVal = sp.getString(key, null);
            byte[] buffer = Base64.decode(objectVal, Base64.DEFAULT);
            ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                T t = (T) ois.readObject();
                return t;
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (bais != null) {
                        bais.close();
                    }
                    if (ois != null) {
                        ois.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /***
     * 只适用于最近单的json - > map 其他的不要用
     *
     * @param s
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static Map parserToMap(String s) {
        Map map = new HashMap();
        JSONObject json;
        try {
            json = new JSONObject(s);
            Iterator keys = json.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String value = json.get(key).toString();
                if (value.startsWith("{") && value.endsWith("}")) {
                    map.put(key, parserToMap(value));
                } else {
                    map.put(key, value);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @param jo      json对象
     * @param rstList
     */
    public static void JsonObject2HashMap(JSONObject jo, List<Map<?, ?>> rstList) {
        for (Iterator<String> keys = jo.keys(); keys.hasNext(); ) {
            try {
                String key1 = keys.next();
                System.out.println("key1---" + key1 + "------" + jo.get(key1)
                        + (jo.get(key1) instanceof JSONObject) + jo.get(key1)
                        + (jo.get(key1) instanceof JSONArray));
                if (jo.get(key1) instanceof JSONObject) {

                    JsonObject2HashMap((JSONObject) jo.get(key1), rstList);
                    continue;
                }
                if (jo.get(key1) instanceof JSONArray) {
                    JsonArray2HashMap((JSONArray) jo.get(key1), rstList);
                    continue;
                }
                System.out.println("key1:" + key1 + "----------jo.get(key1):" + jo.get(key1));
                json2HashMap(key1, jo.get(key1), rstList);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    public static void JsonArray2HashMap(JSONArray joArr, List<Map<?, ?>> rstList) {
        for (int i = 0; i < joArr.length(); i++) {
            try {
                if (joArr.get(i) instanceof JSONObject) {

                    JsonObject2HashMap((JSONObject) joArr.get(i), rstList);
                    continue;
                }
                if (joArr.get(i) instanceof JSONArray) {

                    JsonArray2HashMap((JSONArray) joArr.get(i), rstList);
                    continue;
                }
                System.out.println("Excepton~~~~~");

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * json 转换为map
     *
     * @param key
     * @param value
     * @param rstList
     */
    public static void json2HashMap(String key, Object value, List<Map<?, ?>> rstList) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(key, value);
        rstList.add(map);
    }

    /***
     * 消除字符串 最后的0或者.
     *
     * @param temp
     * @return
     */
    public static String getRealValue(String temp) {
        if (null == temp || temp.trim().toString().equals("")) {
            return "0";
        }
        if (temp.equals("0.0")) {
            return "0";
        }
        // 如果包含小数点
        if (temp.contains(".")) {
            while (temp.endsWith("0")) {
                temp = temp.substring(0, temp.length() - 1);
            }
            // 并且是最后一个的时候
            if (temp.endsWith(".")) {
                return temp.substring(0, temp.length() - 1);
            }
            try {
                Integer valueOf = Integer.valueOf(temp);
                if (Integer.valueOf("0") == valueOf) {
                    return "0";
                } else {
                    return temp;
                }
            } catch (Exception e) {
            } finally {
                return temp;
            }

        } else {
            while (temp.startsWith("0")) {
                temp = temp.substring(0, temp.length() - 1);
            }
        }
        if (temp.equals(".")) {
            temp = "0";
        }
        if (temp.startsWith(".")) {
            temp = "0" + temp + "0";
        }
        if (temp.equals("")) {
            temp = "0";
        }
        return temp;
    }

    private static byte[] getRawKey() throws NoSuchAlgorithmException {
        SecureRandom sr = SecureRandom.getInstance("yonyoujryidongyingyongetc"); // 获得一个随机数，传入的参数为默认方式。
        // sr.setSeed(seed); // 设置一个种子，这个种子一般是用户设定的密码。也可以是其它某个固定的字符串
        sr.setSeed("yonyoujryidongyingyongetc".getBytes()); // 设置一个种子，这个种子一般是用户设定的密码。也可以是其它某个固定的字符串
        KeyGenerator keyGen = KeyGenerator.getInstance("AES"); // 获得一个key生成器（AES加密模式）
        keyGen.init(128, sr); // 设置密匙长度128位
        SecretKey key = keyGen.generateKey(); // 获得密匙
        byte[] raw = key.getEncoded(); // 返回密匙的byte数组供加解密使用
        return raw;
    }

    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES"); // KeyGenerator提供（对称）密钥生成器的功能。使用getInstance
            // 类方法构造密钥生成器。
            kgen.init(128, new SecureRandom(password.getBytes()));// 使用用户提供的随机源初始化此密钥生成器，使其具有确定的密钥大小。
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 使用SecretKeySpec类来根据一个字节数组构造一个
            // SecretKey,，而无须通过一个（基于
            // provider
            // 的）SecretKeyFactory.
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器 //为创建 Cipher
            // 对象，应用程序调用 Cipher 的
            // getInstance 方法并将所请求转换
            // 的名称传递给它。还可以指定提供者的名称（可选）。
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent); // 按单部分操作加密或解密数据，或者结束一个多部分操作。数据将被加密或解密（具体取决于此
            // Cipher 的初始化方式）。
            System.out.println("加密后：" + result);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }




    /*********************** sha1 算法  start  ****************************/
    /**
     * 使用方法  Encrypt(strSrc,"SHA-1")
     * @param strSrc
     * @param encName
     * @return
     */
    public String Encrypt(String strSrc,String encName) {
        //parameter strSrc is a string will be encrypted,
        //parameter encName is the algorithm name will be used.
        //encName dafault to "MD5"
        MessageDigest md=null;
        String strDes=null;

        byte[] bt=strSrc.getBytes();
        try {
            if (encName==null||encName.equals("")) {
                encName="MD5";
            }
            md=MessageDigest.getInstance(encName);
            md.update(bt);
            strDes=bytes2Hex(md.digest());  //to HexString
        }
        catch (NoSuchAlgorithmException e) {
            LogUtils.e(e);
            return null;
        }
        return strDes;
    }


    public String bytes2Hex(byte[]bts) {
        String des="";
        String tmp=null;
        for (int i=0;i<bts.length;i++) {
            tmp=(Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length()==1) {
                des+="0";
            }
            des+=tmp;
        }
        return des;
    }

    /*********************** sha1 算法   end ****************************/

}